import { Context } from 'koa'
import { z } from 'zod'
import { prisma } from '../../lib/database'

// 验证 schema
const getUsersQuerySchema = z.object({
    page: z.string().optional().transform(val => val ? parseInt(val) : 1),
    limit: z.string().optional().transform(val => val ? parseInt(val) : 10),
    search: z.string().optional()
})

// 获取用户列表接口 (Demo 接口)
export default async function getUsers(ctx: Context): Promise<void> {
    try {
        const query = getUsersQuerySchema.parse(ctx.query)
        const { page, limit, search } = query

        const skip = (page - 1) * limit

        // 构建查询条件
        const where = search
            ? {
                OR: [
                    { username: { contains: search } },
                    { nickname: { contains: search } },
                    { email: { contains: search } }
                ]
            }
            : {}

        // 获取用户总数
        const total = await prisma.user.count({ where })

        // 获取用户列表
        const users = await prisma.user.findMany({
            where,
            skip,
            take: limit,
            select: {
                id: true,
                email: true,
                username: true,
                nickname: true,
                avatar: true,
                bio: true,
                createdAt: true,
                updatedAt: true,
                _count: {
                    select: {
                        posts: true,
                        comments: true
                    }
                }
            },
            orderBy: {
                createdAt: 'desc'
            }
        })

        ctx.body = {
            success: true,
            message: 'Users retrieved successfully',
            data: {
                users,
                pagination: {
                    page,
                    limit,
                    total,
                    totalPages: Math.ceil(total / limit),
                    hasNext: page * limit < total,
                    hasPrev: page > 1
                }
            }
        }
    } catch (error) {
        throw error
    }
}
